// store/useUserStore.js 或 stores/userStore.js
import Cookies from 'js-cookie';
import { create } from 'zustand';

// 定义初始用户状态
const initialUserState = {
  userInfo: null, // 存储用户详细信息，如 { id, name, email, avatar, role }
  token: Cookies.get('auth') || '',    // 存储认证 token
  isLogin: Cookies.get('auth') ? true : false, // 标记用户是否已认证
  resources: [], // 存储用户菜单资源
  loading: false, // 菜单加载状态
};

export interface UserStore {
  userInfo: any;
  token: string;
  isLogin: boolean;
  resources: any[];
  loading: boolean;
  setUserInfo: (userInfo: any) => void;
  updateUserInfo: (newUserInfo: any) => void;
  setToken: (token: string) => void;
  setIsLogin: (isLogin: boolean) => void;
  setResources: (resources: any[]) => void;
  setLoading: (loading: boolean) => void;
  login: (token: string, userInfo: any) => void;
  logout: () => void;
  updateResources: (resources: any[]) => void;
}

// 创建 store
const useUserStore = create<UserStore>(
  (set, get) => ({
    ...initialUserState,
    
    setUserInfo: (userInfo: any) => {
      set({ userInfo });
    },
    
    updateUserInfo: (newUserInfo: any) => {
      set((state: any) => ({ userInfo: { ...state.userInfo, ...newUserInfo } }));
    },
    
    setToken: (token: string) => {
      set({ token });
    },
    
    setIsLogin: (isLogin: boolean) => {
      set({ isLogin });
    },
    
    setResources: (resources: any[]) => {
      set({ resources });
    },
    
    setLoading: (loading: boolean) => {
      set({ loading });
    },
    
    // 登录方法：设置token和用户信息
    login: (token: string, userInfo: any) => {
      // 存储到cookie和localStorage
      Cookies.set("auth", token, {
        expires: 30,
        path: "/",
      });
      localStorage.setItem("auth", token);
      localStorage.setItem("user", JSON.stringify(userInfo));
      // 更新store状态
      set({ 
        token, 
        userInfo, 
        isLogin: true,
        resources: [], // 清空之前的菜单
        loading: true // 开始加载菜单
      });
    },
    
    // 登出方法：清除所有认证信息
    logout: () => {
      // 清除cookie和localStorage
      Cookies.remove("auth", { path: "/" });
      localStorage.removeItem("auth");
      localStorage.removeItem("user");
      
      // 重置store状态
      set({
        token: '',
        userInfo: null,
        isLogin: false,
        resources: [],
        loading: false
      });
    },
    
    // 更新菜单资源
    updateResources: (resources: any[]) => {
      set({ 
        resources,
        loading: false
      });
    },
  })
);

export default useUserStore;